package top.fullj.http;

import okhttp3.*;
import okio.BufferedSink;
import okio.GzipSink;
import okio.Okio;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;

import static com.google.common.net.HttpHeaders.CONTENT_ENCODING;

/**
 * @author bruce.wu
 * @since 2021/9/22 11:18
 */
public class GzipRequestInterceptor implements Interceptor {

    @Nonnull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originRequest = chain.request();
        if (originRequest.body() == null
                || originRequest.header(CONTENT_ENCODING) != null) {
            return chain.proceed(originRequest);
        }
        Request gzipRequest = originRequest.newBuilder()
                .header(CONTENT_ENCODING, "gzip")
                .method(originRequest.method(), new GzipRequestBody(originRequest.body()))
                .build();
        return chain.proceed(gzipRequest);
    }

    private static class GzipRequestBody extends RequestBody {

        private final RequestBody body;

        GzipRequestBody(RequestBody body) {
            this.body = body;
        }

        @Nullable
        @Override
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public void writeTo(@Nonnull BufferedSink sink) throws IOException {
            try (BufferedSink gzSink = Okio.buffer(new GzipSink(sink))) {
                body.writeTo(gzSink);
            }
        }
    }

}
